import express from 'express';
import path from 'path';
import cors from 'cors';
import swaggerUi from 'swagger-ui-express';
import swaggerJsdoc from 'swagger-jsdoc';
import dotenv from 'dotenv';

// 加载环境变量
dotenv.config();

// Swagger文档配置
const options = {
  definition: {
    openapi: '3.0.0',
    info: {
      title: 'Node服务器 API文档',
      version: '1.0.0',
      description: '使用OpenAPI/Swagger记录的API接口文档',
      license: {
        name: 'MIT',
        url: 'https://opensource.org/licenses/MIT',
      },
      contact: {
        name: '开发团队',
        url: 'https://example.com',
        email: 'support@example.com',
      },
    },
    servers: [
      {
        url: `http://localhost:${process.env.PORT || 3000}/api`,
        description: 'API服务器',
      },
    ],
  },
  // 指定API定义文件的位置
  apis: [
    './src/doc/openapi/**/*.yaml',
    './src/doc/openapi/**/*.json',
    './src/doc/components/**/*.yaml',
    './src/doc/paths/**/*.yaml',
  ],
};

const swaggerSpec = swaggerJsdoc(options);
const app = express();

// 基本配置
app.use(cors());
app.use(express.json());
app.use(express.static(path.join(__dirname, '../../public')));

// Swagger路由
app.use('/', swaggerUi.serve);
app.get('/', swaggerUi.setup(swaggerSpec, {
  explorer: true,
  customCss: '.swagger-ui .topbar { display: none }',
  swaggerOptions: {
    docExpansion: 'none',
    persistAuthorization: true,
    filter: true,
  }
}));

// 提供JSON格式的API规范
app.get('/swagger.json', (req, res) => {
  res.setHeader('Content-Type', 'application/json');
  res.send(swaggerSpec);
});

// 确定端口
const PORT = process.env.SWAGGER_PORT || 3001;

// 启动Swagger文档服务器
app.listen(PORT, () => {
  console.log(`API文档服务已启动: http://localhost:${PORT}`);
}); 